package com.deli.springboot.NioAndIoDemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;


public class NioServerDemo {
    private Selector selector;

    public static void main(String[] args) {
        NioServerDemo nioServerDemo = new NioServerDemo();
        nioServerDemo.initServer(8000);

    }
    public void initServer(int port) {
        try {
            //获得一个socket的通道
            ServerSocketChannel socketChannel = ServerSocketChannel.open();
            //设置通道为非阻塞性
            socketChannel.configureBlocking(false);
            //将端口号绑定到socket通道
            socketChannel.socket().bind(new InetSocketAddress(port));
            //获得通道管理器
            this.selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void listen(){
        System.out.println("服务端开始了");
        try {
            selector.select();
            while(true){
                Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
                while(iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    handler(key);
                }
            }
        } catch (IOException e) {


        }
    }

    private void handler(SelectionKey key) {
        if (key.isAcceptable()){
            handlerAccept(key);
        }else if(key.isReadable()){
            handlerReadable(key);
        }
    }

    private void handlerReadable(SelectionKey key) {
        SocketChannel channel = (SocketChannel) key.channel();

    }

    private void handlerAccept(SelectionKey key) {
        ServerSocketChannel channel = (ServerSocketChannel) key.channel();
        try {
            SocketChannel accept = channel.accept();
            accept.configureBlocking(false);
            System.out.println("客户端连接");
            channel.register(this.selector,SelectionKey.OP_READ);
        } catch (IOException e) {


        }

    }
}
